<!--
*@Author: QWP
*@Description: 悬浮聊天信息
*@Date: 2024-11-21 16:19:41
-->
<template>
  <!-- 消息浮动图标按钮 -->
  <a-float-button shape="circle" 
    type="primary" 
    style="right: 20px; bottom: 70px" 
    :badge="{ count: unReadMsgCount }"
    @click="showChat = true; unReadMsgCount = 0, currentUser = null">
    <template #icon>
      <BellOutlined style="font-size: 20px; color: #fff" />
    </template>
  </a-float-button>

  <!-- 展示群聊弹窗 -->
  <ChatDialog v-model:open="showChat" 
    width="65%" 
    :isDialog="true" 
    :currentUser="currentUser"
    :keyUnNumber="keyUnNumber"
    @close="showChat = false;" 
  />
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, watch, onUnmounted } from 'vue' 
import { useLoginStore } from '@/store'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import { notification } from 'ant-design-vue';
import * as chatApi from '@/service/emergency/chat'
import * as loginApi from '@/service/login'
import useWebSocket from '@/hooks/useWebsockt'
import { api } from '@/http/api'
import { chatEventBus } from '@/util/eventBus'
import ChatDialog from '@/views/oa/emergency/group/chat/ChatDialog.vue'
import { numberC } from '@/util/common'
import { addC } from '@/util/computePtrcision.ts'

const route = useRoute()
const router = useRouter()
const loginStore = useLoginStore()
const { userInfo, token } = storeToRefs(loginStore)

const showChat = ref<boolean>(false)

// 获取聊天未读的消息数
const keyUnNumber = ref<object>({})
const unReadMsgCount = ref<number>(0)
const { open, close, reconnect, on, send } = useWebSocket({
  url: `ws://${api.replace('http://', '')}/bizz/chatServer/${userInfo.value['userId']}/${userInfo.value['name']}/web`
});
const getUnreadMsg = async () => {
  open()
  try {
    const res = await chatApi.getMessage({
      current: 1,
      model: {},
      size: 5000,
    });
    if (res.code == 0) {
      let groupList = res.data.chatList.groupList.records || [];
      let total = [0, ...groupList.map(o => numberC(o['numbers']))].reduce((a, b) => addC(a, b))
      keyUnNumber.value = groupList.reduce((acc, curr) => {
        acc[curr['keyid']] = numberC(curr['numbers'])
        return acc
      }, {})
    }
  } catch (error) { }

  getRealNoredMsg()
}

// 获取实时消息
const getRealNoredMsg = () => {
  on('message', (data) => {

    // 消息内容接收
    chatEventBus.emit('allRealMsg', data)

    // 上下线
    if(data['messageType'] == 7) {
      // 强制下线
      if(data['onlineStatus'] == 0 && data['isOffline'] == 1) {
        logOut()
      }
      return
    }

    if (data) {
      const message = data || {}
      const { chatType, sender, groupId, messageId } = message

      // 实时修改群列表
      chatEventBus.emit('realMsg', message)

      // 系统通知
      if(data['messageType'] == '4') {
        if(!keyUnNumber.value[messageId]) keyUnNumber.value[messageId] = 0
        keyUnNumber.value[messageId] = 1
      }

      if (!chatType || route.path == '/TransitIndex/EmergencyChat' || showChat.value == true) {
        return
      }

      // 设置未读消息个数
      const matchId = { 1: 'groupId', 2: 'sender' }
      const groupId1 = message[matchId[chatType]] || ''
      if(!keyUnNumber.value[groupId1]) {
        keyUnNumber.value[groupId1] = 0
      }
      if(groupId1) {
        keyUnNumber.value[groupId1] += 1
      }
    }
  })

  on('close', () => {})
}

// APP端强制下线
let logOutIndex = 0;
const logOut = async () => {
  if(logOutIndex != 0) {
    return
  }
  logOutIndex ++;
  try {
    const res =  await loginApi.logout({
      userid: userInfo.value['userId'],
      clientType: 'web'
    })
    if(res.code == 0) {
      loginStore.setRefreshToken('')
      loginStore.setToken('')
      
      notification.warning({
        message: '提示',
        description: '退出成功！',
        placement: 'topLeft',
        duration: null
      });
      router.push('/')
    }
    else {
      messageC(res.data.msg, "error")
    }
  } catch (error) {}
}

const currentUser = ref<object | null>(null);
onMounted(() => {
  getUnreadMsg()
  chatEventBus.on('setFloatUnNum', ({ keyid, value }) => {
    keyUnNumber.value[keyid] = value
  })

  // 打开指定群聊
  chatEventBus.on('openGroup', (data) => {
    currentUser.value = data;
    showChat.value = true
  })

  window.addEventListener('beforeunload', function() {
    close(true)
  });
})

watch(() => token.value, (nval) => {
  if(nval == '') {
    close(true)
  }
}, { immediate: true })

watch(() => keyUnNumber, (nval) => {
  unReadMsgCount.value = [0, ...Object.values(keyUnNumber.value)].reduce((a, b) => addC(a, b))
}, { immediate: true, deep: true })

</script>

<style lang='scss' scoped>
</style>